<template>
	<view>
		<!-- 搜索框 -->
		<view class="search-box">
			<uni-search-bar @input="input" :radius="100" cancelButton="none" cancelText="搜索" @confirm="gotoGoodsList">
			</uni-search-bar>
		</view>
		<!-- 搜索建议列表 -->
		<view class="sugg-list" v-if="searchResults.length !==0">
			<view class="sugg-item" v-for="(item, i) in searchResults" :key="i" @click="gotoDetail(item.goods_id)">
				<view class="goods-name">{{ item.goods_name }}</view>
				<uni-icons type="arrowright" size="16"></uni-icons>
			</view>
		</view>
		<!-- 搜索历史 -->
		<view class="history-box" v-else>
			<!-- 标题区域 -->
			<view class="history-title">
				<text>搜索历史</text>
				<uni-icons type="trash" size="20" @click="cleanHistory"></uni-icons>
			</view>
			<!-- 列表区域 -->
			<view class="history-list">
				<text class="history-item" v-for="(item,index) in historys" :key="index"
					@click="gotoGoodsList(item)">{{item}}</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 延时器的 timerId
				timer: null,
				// 搜索关键词
				kw: '',
				// 搜索结果列表
				searchResults: [],
				// 搜索关键词历史
				historyList: []
			};
		},
		computed: {
			historys() {
				return [...this.historyList].reverse();
			}
		},
		onLoad() {
			this.historyList = JSON.parse(uni.getStorageSync('kw') || '[]');
		},
		methods: {
			input(value) {
				clearTimeout(this.timer);
				// 如果 500 毫秒内，没有触发新的输入事件，则为搜索关键词赋值
				this.timer = setTimeout(() => {
					this.kw = value;
					this.getSearchList();
				}, 500)
			},
			// 根据搜索关键词，搜索商品建议列表
			async getSearchList() {
				if (this.kw === '') {
					this.searchResults = [];
					return
				}
				const {
					data: res
				} = await uni.$http.get('/goods/qsearch', {
					query: this.kw
				});
				if (res.meta.status !== 200) return uni.$showMsg();
				this.searchResults = res.message;
				this.saveSearchHistory();
			},
			// 点击搜索建议的 Item 项，跳转到商品详情页面
			gotoDetail(goods_id) {
				uni.navigateTo({
					url: '/subpkg/goods_detail/goods_detail?goods_id=' + goods_id
				})
			},
			// 点击跳转到商品列表页面
			gotoGoodsList(val) {
				const key = val.value ? val.value : val
				uni.navigateTo({
					url: '/subpkg/goods_list/goods_list?query=' + key
				})
			},
			// 保存搜索关键词
			saveSearchHistory() {
				// this.historyList.push(this.kw);
				// 将 Array 数组转化为 Set 对象
				const set = new Set(this.historyList);
				set.delete(this.kw);
				set.add(this.kw);
				// 将 Set 对象转化为 Array 数组
				this.historyList = Array.from(set);
				// 调用 uni.setStorageSync(key, value) 将搜索历史记录持久化存储到本地
				uni.setStorageSync('kw', JSON.stringify(this.historyList));
			},
			// 清除历史记录
			cleanHistory() {
				this.historyList = [];
				uni.setStorageSync('kw', '[]')
			}
		}
	}
</script>

<style lang="scss">
	.sugg-list {
		padding: 0 10px;

		.sugg-item {
			font-size: 12px;
			padding: 13px 0;
			border-bottom: 1px solid #efefef;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.goods-name {
				// 文字不允许换行（单行文本）
				white-space: nowrap;
				// 溢出部分隐藏
				overflow: hidden;
				// 文本溢出后，使用 ... 代替
				text-overflow: ellipsis;
				margin-right: 5px;
			}
		}
	}

	.history-box {
		padding: 0 10px;

		.history-title {
			display: flex;
			justify-content: space-between;
			align-items: center;
			height: 40px;
			font-size: 16px;
			border-bottom: 1px solid #efefef;
		}

		.history-list {
			display: flex;
			flex-wrap: wrap;

			.history-item {
				font-size: 14px;
				border-radius: 10px;
				padding: 5px 10px;
				margin-top: 5px;
				margin-right: 5px;
				background-color: #efefef;
			}
		}
	}
</style>
